<?php
 
namespace App\Service;

/*
 * 易宝支付
 */
use App\Service\YoppayUtils\YopConfig;
use App\Service\YoppayUtils\YopClient3;
use App\Service\YoppayUtils\YopRequest;
use Illuminate\Support\Facades\DB;
use App\Common\Base;

class YoppayService 
{

	public static function yoppay($data,$params)
	{ 	
		//获取商户hmacKey		
		$result = self::getHmacKey($data['parentMerchantNo'], $data['merchantNo']);
		if($result['code'] == 666){
			$hmacKey = $result['data'];
		}else{
			return $result['data'];
		}

		$yopData=array();
		$yopData['parentMerchantNo'] 	= $data['parentMerchantNo'];
		$yopData['merchantNo']			= $data['merchantNo'];
		$yopData['orderId']				= $data['orderId'];
		$yopData['orderAmount'] 		= $data['orderAmount'];
		$yopData['notifyUrl']			= $data['notifyUrl'];

		$hmacstr 	= hash_hmac('sha256', Base::toString($yopData), $hmacKey, true);
		$hmac 		= bin2hex($hmacstr);
		$token		= self::order($yopData,$hmac);

		$array = self::APIorder($params,$token);
		if( $array['result'] == NULL)
		{
			return "error!";
		}else{
			$result= $array['result'];
			return $result;
		}
	}

	//获取商户hmacKey	
	public static function getHmacKey($parentMerchantNo, $merchantNo)
	{
		$config = config('app.yeepay');
		$request = new YopRequest($config['appKey'], $config['private_key'], "https://open.yeepay.com/yop-center",$config['yop_public_key']);
	    $request->addParam("parentMerchantNo", $parentMerchantNo);
	    $request->addParam("merchantNo", $merchantNo);
		$response = YopClient3::post("/rest/v1.0/sys/merchant/hmackeyquery", $request);
		$keyResult = Base::object_array($response);

		Base::yibaoLog(1,'hmackey',json_encode($request),json_encode($keyResult));

		if($keyResult['state'] == 'SUCCESS'){
			if($keyResult['result']['returnCode'] == 'REG00000'){
				$hmacKey = $keyResult['result']['merHmacKey'];
				return ['code' => 666, 'data' => $hmacKey];
			}else{
				return ['code' => 1002, 'data' => $keyResult['result']];
			}
			
		}else{
			return ['code' => 1001, 'data' => $keyResult['error']];
		}
	}

	public static function order($data,$hmac)
	{
		$config = config('app.yeepay'); 
	    $request = new YopRequest($config['appKey'],$config['private_key'],"https://open.yeepay.com/yop-center",$config['yop_public_key']);
	    $request->addParam("parentMerchantNo", $data['parentMerchantNo']);
	    $request->addParam("merchantNo", $data['merchantNo']);
	    $request->addParam("orderId", $data['orderId']);
	    $request->addParam("orderAmount", (string)$data["orderAmount"]);
	    $request->addParam("timeoutExpress", "5");
	    $request->addParam("requestDate", date('Y-m-d H:i:s'));
	    $request->addParam("redirectUrl", "");
	    $request->addParam("notifyUrl", $data['notifyUrl']);
	    $request->addParam("goodsParamExt", '{"goodsName":"RealShareProduct","goodsDesc":"good"}');
	    $request->addParam("paymentParamExt", "");
	    $request->addParam("industryParamExt", "");
	    $request->addParam("memo", "");
	    $request->addParam("riskParamExt","");
	    $request->addParam("csUrl","");
	    $request->addParam("fundProcessType", "DELAY_SETTLE");
		$request->addParam("divideDetail","");
		$request->addParam("divideNotifyUrl","");
		
		$request->addParam("hmac", $hmac);
	    //var_dump($request);exit();
	    $response = YopClient3::post("/rest/v1.0/sys/trade/order", $request);
	    //取得返回结果
	    $data=Base::object_array($response);

	    Base::yibaoLog(2,'order_token',json_encode($request),json_encode($data));

		if($data['result']['code'] != 'OPR00000'){
			return $data['result'];
		}
	    $token=$data['result']['token'];
	    self::updateOrder($data['result']['orderId'],$data['result']['uniqueOrderNo']);
	    return $token ;
	  
	}

	public static function APIorder($params,$token)
	{
		$config = config('app.yeepay'); 
	    $request = new YopRequest($config['appKey'],$config['private_key'],"https://open.yeepay.com/yop-center",$config['yop_public_key']); 

	    $request->addParam("token", $token);
	    $request->addParam("payTool", $params['payTool']);
	    $request->addParam("payType", $params['payType']);
	    $request->addParam("userNo", $params['userNo']);
	    $request->addParam("userType", $params['userType']);
	    
	    $request->addParam("appId", $params['appId']);
	    $request->addParam("openId", $params['openId']);
	    $request->addParam("payEmpowerNo", "");
	    $request->addParam("merchantTerminalId", "");
	    $request->addParam("merchantStoreNo", "");
	    $request->addParam("userIp", $params['userIp']);
	    $request->addParam("version", $params['version']);
	    $response = YopClient3::post("/rest/v1.0/nccashierapi/api/pay", $request);
	    $data=Base::object_array($response);

	    Base::yibaoLog(3,'order',json_encode($request),json_encode($data));

	    return $data ;  
	}

	public static function updateOrder($batchcode,$uniqueOrderNo)
	{
	  $orderQuery = DB::table('orders')->where(['batchcode' => $batchcode])->first();
            if($orderQuery == null){
                $unitOrder = DB::table('unit_order')->where(['pay_batchcode' => $batchcode])->first();
                if($unitOrder == null){
                    return DRS::returnError(1001,'找不到该订单');
                }else{
                    $originOrder = DB::table('orders')->where(['batchcode' => $unitOrder->batchcode])->first();
                    
                    DB::table('unit_order')->where(['pay_batchcode' => $batchcode])->update([ 'transaction_id' => $uniqueOrderNo, 'pay_code' => 0, 'update_time' => date('Y-m-d H:i:s') ]);
                }
            }else{
                DB::table('orders')->where(['batchcode' => $batchcode])->update(['uniqueOrderNo'=> $uniqueOrderNo ]);
                DB::table('orders_info')->where(['batchcode' => $batchcode])->update(['pay_batchode'=> $uniqueOrderNo,'last_time' => date('Y-m-d H:i:s')]);
            }
	}
	// 同步的商品进行分账处理，改变订单状态，记录商家不可提现金额
	public static function updateOriginalOrder($order_info)
	{
		$product = DB::table('product')->where(['id' => $order_info->product_id])->first();

		if($product->is_synchro == 1)
		{
			// 找到原始商品的信息
			$sourceProduct = DB::table('product')->where(['id' => $product->source_product_id])->first();
			// 找到原始商家的信息
			$sourceUser 		= DB::table('users')->where(['id' => $sourceProduct->business_id])->first();
			$sourceBusiness 	= DB::table('business')->where(['business_id' => $sourceUser->id])->first();

			// 获取现商家信息
			$business = DB::table('business')->where(['business_id' => $order_info->business_id])->first();

			// 分账传输数据
			$divideRequestId = date('YmdHis').str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
			$data = [
				'parentMerchantNo'	=> $business->parentMerchantNo,
				'merchantNo'		=> $business->merchantNo,
				'orderId'			=> $order_info->batchcode,
				'uniqueOrderNo'		=> $order_info->pay_batchode,
				'divideRequestId'	=> $divideRequestId,
			];

			//获取商户hmacKey		
			$result = self::getHmacKey($data['parentMerchantNo'], $data['merchantNo']);
			if($result['code'] == 666){
				$hmacKey = $result['data'];
			}else{
				return ['code' => 10002, 'data' => $result['data'] ];
			}
			$hmacstr = hash_hmac('sha256', Base::toString($data), $hmacKey, true);
			$hmac = bin2hex($hmacstr);
			// 分账详情
			$divideDetail = '[{"ledgerNo":"'.$sourceBusiness->merchantNo.'","ledgerName":"'.$sourceBusiness->business_name.'","amount":"'.$sourceProduct->peer_price.'"}]';
			// 分账商户间的合同号
			$contractNo = date('YmdHis').str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
			// 向易宝发送分账请求
			$returnDivide = self::divide($data,$hmac,$divideDetail,$contractNo);

			if($returnDivide['code'] == 'OPR00000')
			{
				// 查找原始商品的订单
				$source_order_info = DB::table('orders_info')->where(['user_id' => $product->business_id, 'product_id'=>$product->source_product_id, 'payment_status' => 0,'status'=>1])->first();
				if($source_order_info != null)
				{
					// // 增加一条本商户的不可提现余额记录
					// $money = $order_info->price-$order_info->peer_price;
     //                DB::table('merchant_currency')->insert(['user_id'=>$business->business_id, 'order_info_id'=>$order_info->id,'money'=>round($money,2),'batchcode' =>$order_info->batchcode ,'uniqueOrderNo'=>$order_info->pay_batchode ,'batchcode_info'=>$order_info->info_batchcode,'type' => 1, 'state'=>0,'createtime'=>date('Y-m-d H:i:s')]);
                    // 增加一条原始商户的不可提现余额记录
                    DB::table('merchant_currency')->insert(['user_id'=>$sourceBusiness->business_id,'order_info_id'=>$source_order_info->id, 'money'=>round($sourceProduct->peer_price,2),'batchcode' =>$source_order_info->batchcode ,'uniqueOrderNo'=>$source_order_info->pay_batchode,'batchcode_info'=>$source_order_info->info_batchcode,'type' => 1, 'state'=>0,'createtime'=>date('Y-m-d H:i:s')]);

					// 改变原始订单详情的支付状态和订单状态
					// DB::table('orders_info')->where(['business_id' => $sourceUser->id,'user_id' => $product->business_id, 'product_id'=>$product->source_product_id, 'payment_status' => 0])->update(['payment_status' => 1, 'status'=> 2, 'pay_reatetime' => date('Y-m-d H:i:s')]);
					DB::table('orders_info')->where(['id' => $source_order_info->id])->update(['payment_status' => 1, 'status'=> 2, 'pay_reatetime' => date('Y-m-d H:i:s')]);
					// 改变原始订单的状态和支付状态
					DB::table('orders')->where(['batchcode' => $source_order_info->batchcode])->update(['payment_status' => 1, 'status'=> 2, 'pay_time' => date('Y-m-d H:i:s')]);

					return ['code'=>666, 'data' => ''];
				}
			}else{
				return ['code'=>10001, 'data' => $returnDivide];
			}
		}
		// else{
		// 	// 增加一条本商户的不可提现余额记录
  //           DB::table('merchant_currency')->insert(['user_id'=>$order_info->business_id,'order_info_id'=>$order_info->id,'money'=>$order_info->price,'batchcode' =>$order_info->batchcode ,'uniqueOrderNo'=>$order_info->pay_batchode ,'batchcode_info'=>$order_info->info_batchcode,'type' => 1, 'state'=>0,'createtime'=>date('Y-m-d H:i:s')]);
		// }
	}

	// 发送分账请求
	public static function divide($data,$hmac,$divideDetail,$contractNo)
	{
		$config  = config('app.yeepay');
	    $request = new YopRequest($config['appKey'], $config['private_key'], "https://open.yeepay.com/yop-center",$config['yop_public_key']);
	    $request->addParam("parentMerchantNo", $data['parentMerchantNo']);
	    $request->addParam("merchantNo", $data['merchantNo']);
	    $request->addParam("divideRequestId", $data['divideRequestId']);
	    $request->addParam("orderId", $data['orderId']);
	    $request->addParam("uniqueOrderNo", $data['uniqueOrderNo']);

	    $request->addParam("divideDetail", $divideDetail);
	    $request->addParam("infoParamExt", '');
	    $request->addParam("contractNo", $contractNo);
	    $request->addParam("isUnfreezeResidualAmount", "TRUE");
	    $request->addParam("hmac",$hmac);
	 
	    $response = YopClient3::post("/rest/v1.0/sys/trade/divide", $request);
	    //取得返回结果
	    $data = Base::object_array($response);
	    
	    Base::yibaoLog(4,'divide',json_encode($request),json_encode($data));

	    if($data['state'] == 'SUCCESS'){
	    	return $data['result'];
	    }else{
	    	var_dump($data);exit();
	    }
 	}

 	// 易宝资金确认
    public static function confirmYeepayCurrency($parentMerchantNo,$merchantNo,$batchcode,$uniqueOrderNo)
    {
    	$yeePayConfig = config('app.yeepay');

    	$data=array();
		$data['parentMerchantNo']	= $parentMerchantNo;
		$data['merchantNo']			= $merchantNo;
		$data['orderId']			= $batchcode;
		$data['uniqueOrderNo']		= $uniqueOrderNo;
 		
 		//获取商户hmacKey		
		$result = self::getHmacKey($parentMerchantNo,$merchantNo);
		if($result['code'] == 666){
			$hmacKey = $result['data'];
		}else{
			return ['code' => 10002, 'data' => $result['data'] ];
		}

		$hmacstr = hash_hmac('sha256', Base::toString($data), $hmacKey, true);
		$hmac = bin2hex($hmacstr);

		$request = new YopRequest("OPR:10024438625", $yeePayConfig['private_key'], "https://open.yeepay.com/yop-center",$yeePayConfig['yop_public_key']);
	    $request->addParam("parentMerchantNo", $parentMerchantNo);
	    $request->addParam("merchantNo", $merchantNo);
	    $request->addParam("orderId", $batchcode);
	    $request->addParam("uniqueOrderNo", $uniqueOrderNo);
	    $request->addParam("hmac",$hmac);
	 
	    $response = YopClient3::post("/rest/v1.0/sys/trade/fullsettle", $request);
	    if($response->validSign==1){
	        echo "返回结果签名验证成功!\n";
	    }
    
        //取得返回结果
        $data = Base::object_array($response);
        
        Base::yibaoLog(5,'fullsettle',json_encode($request),json_encode($data));

	    if($data['result'] != null){
	    	return $data['result'];
	    }else{
	    	var_dump($data);exit();
	    }
    }
}